const mysql = require('./../utils/selfDB')
//获取标题信息
function queryArticleList(ctx) {
  var openid = ctx.state.$wxInfo.userinfo.openId; //'用户号' , 
  var functype = ctx.request.body.functype;  // '功能类型 SYSTEM.MENU' , 
  var search = ctx.request.body.search;//查询条件
  var beginseq = ctx.request.body.beginseq * 1;//开始条件
  var querynum = ctx.request.body.querynum * 1;//查询条数

  var rawsql = ' 1'; 
  var varset = {};
  if (search) {
    rawsql = ' (`title` like :search or `indexing` like :search)'
    varset.search = '%' + search + '%'
  }//grade非0的数据不>=querynum，否则报错
  if (beginseq) {
    varset.begin = beginseq
    varset.querynum = querynum
    rawsql = rawsql + ' and  `seqid` < :begin  and `grade` = 0 order by `seqid` desc limit :querynum'//{ search: '%' + search + '%' ,
  } else {
    rawsql = rawsql + ' order by `grade` desc,`seqid` desc limit :querynum';
    varset.querynum = querynum
  }
  return mysql.select('*').from('author_create_title')
    .where({ openid, functype, useflag: '0' }).andWhereRaw(rawsql, varset)
    .then(data => {
      return {
        status: '0',
        msg: data
      }
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "query Article List error:" + e.message
      }
    })
}

//获取内容信息
function queryArticle(ctx) {
  var openid = ctx.request.body.openid; //'用户号' , 
  var seqid = ctx.request.body.seqid;  // '顺序号' , 

  return mysql.select('*').from('author_create_title')
    .where({
      openid, seqid, useflag: '0'
    })
    .orderBy('seqid')
    .then(data => {
      if (data.length>0) {
        return mysql.select('*').from('author_create_detail')
          .where({
            openid, seqid
          })
          .orderBy('orders')
          .then(detailData => {
            return {
              status: '0',
              msg: { openid: data[0].openid, seqid: data[0].seqid, functype: data[0].functype, organize: data[0].organize, activity: data[0].activity, title: data[0].title, indexing: data[0].indexing, author: data[0].author, imageurl: data[0].imageurl, authority: data[0].authority, enddate: data[0].enddate, updatetime: data[0].updatetime, detaildata: detailData }
            }
          })
          .catch(e => {
            return {
              status: '-1',
              msg: "query article titles  error:" + e.message
            }
          })
      } else {
        return {
          status: '-1',
          msg: "该信息被删除，或您无权访问该文件"
        }
      }
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "query article detail  error:" + e.message
      }
    })
}

//初始化标题数据
function addArticle(ctx) {
  var openid = ctx.state.$wxInfo.userinfo.openId; //'用户号' , 
  var seqid = "";//ctx.request.body.seqid;  // '顺序号' , 
  var activity = "";
  //1 删除废旧数据 2初始化新数据
  return mysql.del().from('author_create_title').whereNull('functype').andWhere({ openid })
    .then(function () {
      return mysql.max('seqid as seqid').max('activity as activity').from('author_create_title').where({
        openid
      }).then(data => {
        if (data[0].seqid && data[0].seqid != null) {
          seqid = data[0].seqid * 1 + 1;
        } else {
          seqid = '1';
        }
        if (data[0].activity && data[0].activity != null) {
          activity = data[0].activity * 1 + 1;
        } else {
          activity = '1';
        }

        //插入title表
        return mysql().insert({
          openid, seqid, useflag: '1'
        }).into('author_create_title')
          .then(function () {
            return {
              status: '0',
              msg: { seqid: seqid, activity: activity }
            }
          })
          .catch(e => {
            return {
              status: '-1',
              msg: "insert error:" + e.message
            }
          })
      }).then(msg => {
        return msg
      })
        .catch(e => {
          return {
            status: '-1',
            msg: "select seqid error:" + e.message
          }
        })
    }).then(msg => {
      return msg
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "delete title error:" + e.message
      }
    })


}

function updateArticle(ctx) {
  var openid = ctx.state.$wxInfo.userinfo.openId; //'用户号' , 
  var seqid = ctx.request.body.seqid;  // '顺序号' , 
  var functype = ctx.request.body.functype;  // '功能类型 SYSTEM.MENU' , 
  var organize = ctx.request.body.organize; // '所属组织，个人:ALL，组织:组织编号' , 
  var activity = ctx.request.body.activity; //所属活动，非活动为null，活动为序号
  var title = ctx.request.body.title;  // '标题' ,
  var author = ctx.request.body.author;
  var indexing = ctx.request.body.indexing; // '索引' ,
  var imageurl = ctx.request.body.imageurl;  // '缩略图地址' ,
  var authority = ctx.request.body.authority;  // '授权情况SYSTEM.AUTHORITY' ,
  var enddate = ctx.request.body.enddate;  // '有效期' 
  var detaildata = ctx.request.body.detaildata;//明细数据

  //删除原数据
  return mysql.del().from('author_create_detail').where({ openid, seqid })
    .then(function () {
      //detaildata = JSON.stringify(detaildata).replace(/\|r_openid\|/g, openid).replace(/\|r_seqid\|/g,seqid);
      return mysql('author_create_detail').insert(
        detaildata
      ).then(function () {
        return mysql('author_create_title').update({ functype, organize, activity, title, indexing, author, imageurl, authority, enddate, useflag:'0',updatetime: mysql.fn.now() })
          .where({ openid, seqid })
          .then(function () {
            return {
              status: '0',
              msg: "update data succed"
            }
          })
          .catch(e => {
            return {
              status: '-1',
              msg: "insert detail error:" + e.message
            }
          })
      })
    }).then(msg => {
      return msg
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "update detail error:" + e.message
      }
    })
}

function deleteArticle(ctx) {
  var openid = ctx.state.$wxInfo.userinfo.openId; //'用户号' , 
  var seqid = ctx.request.body.seqid;  // '顺序号' , 

  return mysql('author_create_title').update({ useflag: '1' })
    .where({ openid, seqid })
    .then(function () {
      return {
        status: '0',
        msg: 'delete successed'
      }
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "deleteArticle error:" + e.message
      }
    })
}

module.exports = (ctx, next) => {
  var userinfo = ctx.state.$wxInfo.userinfo;
  if (!userinfo.openId) {
    throw '获取用户信息异常'//wafer2 bug 存在无法获取用户信息的情况，抛出异常，重新授权
  }
  try {
    var opflag = ctx.request.body.opflag;//0获取列表 1查看明细 2新增 3更新 4删除
    if (opflag == '0') {
      return queryArticleList(ctx).then(result => {
        ctx.state.data = result
      })
    } else if (opflag == '1') {
      return queryArticle(ctx).then(result => {
        result.userinfo = userinfo;
        ctx.state.data = result;
      })
    } else if (opflag == '2') {
      return addArticle(ctx).then(result => {
        result.userinfo = userinfo;
        ctx.state.data = result;
      })
    } else if (opflag == '3') {//更新
      return updateArticle(ctx).then(result => {
        ctx.state.data = result
      })
    } else if (opflag == '4') {//删除后返回列表
      return deleteArticle(ctx).then(result => {
        ctx.state.data = result
      })
    }
  } finally {

  }

}